﻿Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Windows.Forms

Friend Class ProgressDialog

    Private pathToConvert As String

    Shared Sub ConvertImage(ByVal fileInfo As FileSystemInfo)
        Dim options As New AppSettings
        FileHandler.LoadOptions(options)

        Dim source As Bitmap = TryCast(Bitmap.FromFile(fileInfo.FullName), Bitmap)
        Dim output As New Bitmap(176, 220, PixelFormat.Format16bppRgb565)

        If options.RotateImages AndAlso source.Width > source.Height Then
            source.RotateFlip(RotateFlipType.Rotate90FlipNone)
        End If
        source.RotateFlip(RotateFlipType.Rotate180FlipX)

        Dim position As Point = Nothing
        Dim targetSize As Size = Nothing
        If options.Sizing = 1 Then
            position = New Point(0, 0)
            targetSize = New Size(176, 220)
        Else
            Dim aspectRatio As Double = CDbl(source.Width) / CDbl(source.Height)
            If aspectRatio >= 176.0 / 220.0 Then
                targetSize = New Size(176, CInt(176.0 / source.Width * source.Height))
            Else
                targetSize = New Size(CInt(220.0 / source.Height * source.Width), 220)
            End If
            position = New Point(CInt((176 - targetSize.Width) / 2), CInt((220 - targetSize.Height) / 2))
        End If

        Dim g As Graphics = Graphics.FromImage(output)
        g.InterpolationMode = options.Quality
        g.FillRectangle(Brushes.Black, New Rectangle(0, 0, 176, 220))
        g.DrawImage(source, New Rectangle(position, targetSize))

        ' Save File
        Dim newFilePath As String = GetNewFilePath(fileInfo.FullName)
        Directory.CreateDirectory(Path.GetDirectoryName(newFilePath))
        output.Save(newFilePath, ImageFormat.Bmp)
    End Sub

    Shared Function GetNewFilePath(ByVal filePath As String) As String
        Dim options As New AppSettings
        FileHandler.LoadOptions(options)

        Dim fileName As String = Path.GetFileNameWithoutExtension(filePath) & ".bmp"
        Dim albumName As String = Path.GetDirectoryName(filePath)
        albumName = Path.GetFileName(albumName)
        Dim pathName As String

        If options.CopyToPlayer Then
            pathName = Path.Combine(options.PlayerPath, "PHOTO")
        Else
            pathName = options.ExportPath
        End If

        Return Path.Combine(Path.Combine(pathName, albumName), fileName)
    End Function

    Shared Function GetImageList(ByVal imagesPath As String) As ArrayList
        Dim dir As New DirectoryInfo(imagesPath)
        Dim filelist As New ArrayList()
        filelist.AddRange(dir.GetFiles("*.jpg"))
        filelist.AddRange(dir.GetFiles("*.jpeg"))
        filelist.AddRange(dir.GetFiles("*.bmp"))
        filelist.AddRange(dir.GetFiles("*.gif"))
        filelist.AddRange(dir.GetFiles("*.png"))
        filelist.AddRange(dir.GetFiles("*.tif"))
        filelist.AddRange(dir.GetFiles("*.tiff"))
        filelist.AddRange(dir.GetFiles("*.emf"))
        filelist.AddRange(dir.GetFiles("*.ico"))
        filelist.AddRange(dir.GetFiles("*.wmf"))
        Return filelist
    End Function


    Private Sub ProgressDialog_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim options As New AppSettings
        FileHandler.LoadOptions(options)

        Dim imgList As ArrayList = GetImageList(Me.pathToConvert)
        pbProgress.Maximum = imgList.Count
        pbProgress.Value = 0
        bgConverter.RunWorkerAsync(imgList)
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        If bgConverter.IsBusy Then
            If MessageBox.Show("Are you sure you want to cancel?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
                bgConverter.CancelAsync()
                Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
                Me.Close()
            End If
        Else
            Me.DialogResult = Windows.Forms.DialogResult.OK
            Me.Close()
        End If
    End Sub

    Private Sub bgConverter_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgConverter.DoWork
        Dim imgList As ArrayList = CType(e.Argument, ArrayList)
        Dim index As Integer
        For Each img As FileInfo In imgList
            index += 1
            bgConverter.ReportProgress(index, img.Name)
            ConvertImage(img)
        Next img
    End Sub

    Private Sub bgConverter_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgConverter.ProgressChanged
        lblStatus.Text = e.UserState.ToString
        pbProgress.Value = e.ProgressPercentage
        Dim dirName As String = System.IO.Path.GetFileName(pathToConvert)
        Me.Text = String.Format("Converting ""{0}"" - ({1}/{2})", dirName, pbProgress.Value, pbProgress.Maximum)
    End Sub

    Private Sub bgConverter_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgConverter.RunWorkerCompleted
        lblStatus.Text = "Conversion Done."
        Cancel_Button.Text = "Close"
        My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep)
        Me.Close()
    End Sub

    Public Overloads Function ShowDialog(ByVal pathToConvert As String) As System.Windows.Forms.DialogResult
        Me.pathToConvert = pathToConvert
        Return MyBase.ShowDialog()
    End Function

End Class
